<?php

namespace app\admin\controller;

use think\Validate;
use app\admin\model\Admin;
use app\admin\model\AdminLog;
use app\admin\model\AdminGroup;
use app\admin\model\AuthGroupName;
use app\admin\model\AuthGroup;

/**
 * 管理员
 * Class Adminer
 * @package app\admin\controller
 */
class Adminer extends Base
{
    protected $model;

    protected function initialize()
    {
        parent::initialize();
        $this->model = Admin::getInstance();
        //$this->model = new Admin();
    }

    // 网站基本设置
    public function index()
    {
        return $this->fetch();
    }

    public function lists()
    {
        $keyword = $this->request->has('keyword') ? $this->request->param('keyword') : '';
        $roleid = $this->request->has('roleid') ? $this->request->param('roleid', 0, 'intval') : 0;
        $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;
        $where = [];
        if (!empty($keyword)) {
            $where[] = ['username|realname', 'like', '%' . urldecode($keyword) . '%'];
        }
        if ($roleid > 0) {
            $where[] = ['role_id', '=', $roleid];
        }
        if ($groupid > 0) {
            $where[] = ['group_id', '=', $groupid];
        }
        if ($this->admin_level == 1) {
            $where[] = ['founder', '=', 0];
            //管理员列表
            $lists = $this->model->where($where)->paginate(2);
            //用户组(只有超管显示)
            $groups = AdminGroup::getInstance()->getList(['limit' => 'all']);
            //套餐名字
            $auth_group_names = AuthGroupName::getInstance()->column('*', 'id');
            //套餐组
            $auth_groups = AuthGroup::getInstance()->column('*', 'id');
        } else {
            $where[] = ['parent_id', '=', $this->admin_id];
            //管理员列表
            $lists = $this->model->where($where)->paginate(2);
            //用户组(只有超管显示)
            $groups = AdminGroup::getInstance()->getList(['where' => ['admin_id' => $this->admin_id], 'limit' => 'all']);
            //套餐名字,子账号不包含管理账号
            $auth_group_names = AuthGroupName::getInstance()->whereIn('admin_id', "0,$this->admin_id")->where(['is_admin' => 0])->column('*', 'id');
            //套餐组
            $auth_groups = AuthGroup::getInstance()->whereIn('creator_id', "0,$this->admin_id")->where(['is_admin' => 0])->column('*', 'id');
        }
        //子账号，用户ID
        $admin_ids = array_column($lists->toArray()['data'], 'id');
        //查询账号登录信息
        $ids = AdminLog::getInstance()->where([['admin_id', 'in', $admin_ids]])->group('admin_id')->order('id desc')->column('max(id) as pkid');
        $loglist = AdminLog::getInstance()->where([['id', 'in', $ids]])->column('*', 'admin_id');
        foreach ($lists as $k => $item) {
            if ($item['group_id'] == 0) {
                $item['group_name'] = '超级管理员';
            } else {
                $item['group_name'] = isset($groups[$item['group_id']]) ? $groups[$item['group_id']]['name'] : '-';
            }
            $name_id = isset($auth_groups[$item['role_id']]) ? $auth_groups[$item['role_id']]['name_id'] : 0;
            if ($item['role_id'] == 0) {
                $item['role_name'] = '超级管理员';
            } else {
                $item['role_name'] = isset($auth_group_names[$name_id]) ? $auth_group_names[$name_id]['name'] : '-';
            }
            $item['ip'] = isset($loglist[$item['id']]) ? $loglist[$item['id']]['ip'] : '-';
            $item['status_info'] = $item['status'] == 1 ? '是' : '否';
            $lists[$k] = $item;
        }
        $this->assign('lists', $lists);
        $this->assign('groups', $groups);
        $this->assign('auth_group_names', $auth_group_names);
        $this->assign('param', ['keyword' => $keyword, 'roleid' => $roleid, 'groupid' => $groupid]);
        //是否在选择套餐下拉框中显示 “添加套餐”
        $this->assign('add_rule', $this->admin_level == 1 ? '' : '<option value="">添加套餐</option>');
        return $this->fetch();
    }


    /**
     * 获取用户信息
     * @return mixed
     */
    public function getInfo()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id < 1) {
            return $this->error("ID非法！");
        }
        $info = $this->model->getOne($id);
        $this->assign($info);
        return $this->success('ok', '', $info);
    }

    /**
     * 修改管理员信息
     * @return mixed|void
     */
    public function publish()
    {
        if ($this->request->isPost()) {
            $post = $this->request->param();
            $post['status'] = $post['status'] = 'on' ? 1 : 0;
            $post['parent_id'] = $this->admin_id;
            $post['role_id'] = 1;//(管理员:1,用户:当前管理员ID)
            $id = isset($post['id']) ? intval($post['id']) : 0;
            //数据验证
            $result = $this->validate($post, $id > 0 ? 'app\admin\validate\Adminer.edit' : 'app\admin\validate\Adminer.add');
            if (true !== $result) {
                return $this->error($result);
            }
            if ($id == 0) {
                if (empty($post['password'])) {
                    return $this->error('密码不能为空');
                }
                unset($post['id']);
            }
            if (empty($post['password'])) {
                unset($post['password']);
            } else {
                $post['password_code'] = random(10);
                $post['password'] = zzcmsPassword($post['password'], $post['password_code']);
            }
            $add_id = $this->model->addData($post);
            if (false === $add_id) {
                return $this->error($this->model->getError());
            }
            if ($id == 0) {
                /**
                 * 超管添加套餐：creator_id=0
                 */
                $default_groups = AuthGroup::getInstance()->getList(['where' => ['source_id' => 0, 'creator_id' => 0]]);
                $datas = [];
                foreach ($default_groups as $item) {
                    $item['source_id'] = $item['id'];
                    $item['creator_id'] = $item['is_admin'] == 1 ? 1 : $add_id;
                    unset($item['id'], $item['create_time'], $item['update_time']);
                    $datas[] = $item;
                }
                AuthGroup::getInstance()->saveAll($datas);
            } else {
                $add_id = $id;
            }
            $info = $this->model->getOne($add_id);
            $info['auth_name'] = AuthGroup::getInstance()->where(['id' => $info['role_id']])->value('title');
            $info['group_name'] = AdminGroup::getInstance()->where(['id' => $info['group_id']])->value('name');
            $info['ip'] = '-';
            $info['lasttime'] = '-';
            $info['status_info'] = '正常';
            return $this->success('新增成功', '', $info);
        } else {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $info = [];
            if ($id > 0) {
                $info = $this->model->getOne($id);
            } else {
                $info['parentid'] = 0;
            }
            $info['grouplist'] = getCache('auth_group');
            $info['rulelist'] = getCache('auth_group');
            $this->assign($info);
            return $this->fetch();
        }
    }

    /**
     * 删除管理员时，还需要删除管理员下的权限分组，及其下的用户
     * @return mixed
     */
    public function delete()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id < 2) {
            return $this->error("ID非法！");
        }
        $info = $this->model->getOne($id);
        if ($info['parent_id'] == 0) {
            /*
             * 此为超管操作，先删除子账号，设置子账号下的用户为删除状态
             */
            if ($this->model->where(['id' => $id])->setField(['status' => 2, 'update_time' => time()])) {
                $this->model->where(['parent_id' => $id])->setField(['status' => 2, 'update_time' => time()]);
                return $this->success("删除成功！");
            } else {
                return $this->error($this->model->getError());
            }
        } else {
            /**
             * 此为子账号操作，设置子账号下的用户为删除状态
             */
            $this->model->where(['parent_id' => $id])->setField(['status' => 2, 'update_time' => time()]);
            return $this->success("删除成功！");
        }
    }

    /**
     * 超管可以修改所有子账号及用户，
     */
    public function password()
    {
        if ($this->request->isPost()) {
            $post = $this->request->param();
            if (empty($post['password'])) {
                return $this->error('密码不能不空');
            }
            if ($post['password'] != $post['confirm_password']) {
                return $this->error('两次输入密码不一样');
            }
            $info = $this->model->getOne($this->admin_id);
            if ($info['password'] != zzcmsPassword($post['password'], $info['password_code'])) {
                return $this->error('原始密码错误');
            }
            $data = ['id' => $this->admin_id];
            $data['password'] = zzcmsPassword($post['password'], $info['password_code']);
            if (false === $this->model->editData($data)) {
                return $this->error('修改信息错误');
            } else {
                return $this->success('修改成功');
            }
        } else {
            $this->assign($this->admin_info);
            return $this->fetch();
        }
    }

    ###########################################################用户组管理################################################################
    /**
     * 修改用户信息
     */
    public function groupList()
    {
        //管理员列表
        $lists = AdminGroup::getInstance()->getList();
        $this->assign('lists', $lists);
        return $this->fetch('groupList');
    }

    /**
     * 用户组添加
     */
    public function groupPublish()
    {
        if (!$this->request->isPost()) {
            return $this->error('非法操作');
        }
        $post = $this->request->param();
        $validate = Validate::make([
            'name' => 'require|unique:admin_group,name,0,id',
        ],
            [
                'name.require' => '分组名称不能为空',
                'name.unique' => '分组名称已存在',
            ]);
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }
        $post['admin_id'] = $this->admin_id;
        $post['status'] = isset($post['status']) ? 1 : 0;
        $post['listorder'] = intval($post['listorder']);
        if (isset($post['id'])) {
            unset($post['id']);
        }
        $model = AdminGroup::getInstance();
        $add_id = $model->addData($post);
        if (false === $add_id) {
            return $this->error($model->getError());
        } else {
            $info = $model->getOne($add_id);
            $this->success('新增成功', url('grouplist'), $info);
        }
    }

    /**
     * 用户组修改
     */
    public function groupEdit()
    {
        if (!$this->request->isPost()) {
            return $this->error('非法操作');
        }
        $post = $this->request->param();
        $id = isset($post['id']) ? intval($post['id']) : 0;
        if ($id < 1) {
            return $this->error('参数错误');
        }
        $validate = Validate::make([
            'name' => 'require|unique:admin_group,name,' . $id . ',id',
        ],
            [
                'name.require' => '分组名称不能为空',
                'name.unique' => '分组名称已存在',
            ]);
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }
        $post['status'] = isset($post['status']) ? 1 : 0;
        $post['listorder'] = intval($post['listorder']);
        $model = AdminGroup::getInstance();
        if ($model->editData($post)) {
            return $this->success('修改成功', url('grouplist'));
        } else {
            return $this->error($model->getError());
        }

    }


    /**
     * 用户组删除
     * @return mixed
     */
    public function groupDelete()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id < 1) {
            return $this->error("ID非法！");
        }
        $model = AdminGroup::getInstance();
        $info = $model->getOne($id);
        if (empty($info)) {
            return $this->error('分组不存在');
        }
        if (!($this->admin_level == 1 || $info['admin_id'] == $this->admin_id)) {
            return $this->error('您无权限');
        }
        $num = $model->destroy($id);
        if ($num != 1) {
            return $this->error($model->getError());
        } else {
            return $this->success("删除成功！");
        }
    }

}
